<?php

namespace App\Http\Controllers\Auth;

use Validator;
use App\Model\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Controller;
use \App\Model\JSONResponse as CodeBaseResponse;

class LoginController extends Controller
{
    /**
     * 构造函数
     *
     * @return void
     */
    public function __construct()
    {
        // $this->middleware('guest')->except('logout');
    }

    /**
     * 验证函数
     *
     * @param array $data 待验证数据
     *
     * @return Validator
     *
     * @var \Illuminate\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'phone' => [
                'bail',
                'required',
                'string',
                'regex:/\d/',
                'size:11',
            ],
            'password' => [
                'required',
                'min:6',
                'max:512',
            ],
        ]);
    }

    /**
     * 用户登陆
     *
     * @param data 登陆数据
     * @return json
     */
    public function index(Request $request)
    {
        $data = $request->all();
        $validator = $this->validator($data);
        if ($validator->fails()) {
            return response()->json(CodeBaseResponse::error($validator->errors()));
        }
        $user = User::where('phone', $data['phone'])->first();
        if (!$user) {
            return response()->json(CodeBaseResponse::loginError());
        }
        $hashed_password = $user->password;
        if (Hash::check($data['password'], $hashed_password)) {
            return response()->json(CodeBaseResponse::success('用户登陆成功', [
                'userdata' => $user,
            ]));
        }
        return response()->json(CodeBaseResponse::loginError());
    }
}
